package cn.practice.chat.security;

import cn.hutool.json.JSONUtil;
import cn.practice.chat.feign.UserApiFeign;
import cn.practice.chat.lang.Result;
import cn.practice.chat.response.user.LoginUser;
import cn.practice.chat.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName 登陆成功处理器
 * @Description:
 * @Author A-TAO
 * @Date 2022/10/19
 * @Version V1.0
 **/
@Slf4j
@Component
public class LoginSuccessHanlder implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserApiFeign userApiFeign;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("开始进入LoginSuccessHanlder");
        response.setContentType("application/json;charset=UTF-8");
        String username =  request.getParameter("username");
        log.info("获取到当前登录的用户：{}", username);
        ServletOutputStream outputStream = response.getOutputStream();
        //生成jwt 。 并放置到请求头中
        String token = jwtUtils.generateToken(username);
        Result<LoginUser> userResult = userApiFeign.getUser(username);
        log.info("调用user服务查询用户详情，userResult={}", userResult);
        LoginUser entity = userResult.getData();
        if(entity != null){
            entity.setToken(token);
        }
        Result result = Result.success(entity);
        log.info("登录成功，result={}", result);
        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}
